<template>
    <div class="create-supplier-container">
        <div class="form-wrapper">
            <!-- 供应商信息部分 -->
            <el-card class="form-card" shadow="never">
                <div class="section-header">
                    <h3 class="section-title">供应商信息</h3>
                </div>
                <el-form ref="supplierFormRef" :model="supplierForm" :rules="rules" label-width="120px"
                    class="supplier-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="供应商编码">
                                <el-input v-model="supplierForm.supplierCode" placeholder="自动获取系统编号"
                                    class="readonly-input" readonly>
                                    <template #append>
                                        <el-button @click="generateSupplierCode" :loading="generatingSupplierCode">
                                            自动生成
                                        </el-button>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="供应商名称" prop="supplierName">
                                <el-input v-model="supplierForm.supplierName" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="所属行业" prop="industryId">
                                <el-select v-model="supplierForm.industryId" placeholder="请选择" clearable filterable
                                    style="width: 100%">
                                    <el-option v-for="item in industryList" :key="item.industryId"
                                        :label="item.industryName" :value="item.industryId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="供应商分类" prop="supplierTypeId">
                                <el-select v-model="supplierForm.supplierTypeId" placeholder="请选择" clearable filterable
                                    style="width: 100%">
                                    <el-option v-for="item in supplierTypeList" :key="item.supplierTypeId"
                                        :label="item.supplierTypeName" :value="item.supplierTypeId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="联系人">
                                <el-input v-model="supplierForm.contact" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话">
                                <el-input v-model="supplierForm.contactNumber" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="电子邮箱">
                                <el-input v-model="supplierForm.supplierEmail" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="进货部门">
                                <el-input v-model="supplierForm.organizationName" placeholder="请选择进货部门" readonly
                                    @click="openOrgDialog" style="cursor: pointer;">
                                    <template #suffix>
                                        <el-icon>
                                            <Search />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="进货负责人">
                                <el-input v-model="supplierForm.userName" placeholder="请选择进货负责人" readonly
                                    @click="openUserDialog" style="cursor: pointer;">
                                    <template #suffix>
                                        <el-icon>
                                            <Search />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                <el-radio-group v-model="supplierForm.supplierStatus">
                                    <el-radio :label="0">启用</el-radio>
                                    <el-radio :label="1">停用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="供应商地址">
                                <el-input v-model="supplierForm.supplierAddress" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="备注">
                                <el-input v-model="supplierForm.remarks" type="textarea" :rows="4" placeholder="请输入"
                                    maxlength="500" show-word-limit />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <!-- 财务信息部分 -->
            <el-card class="form-card" shadow="never">
                <div class="section-header">
                    <h3 class="section-title">财务信息</h3>
                </div>
                <el-form :model="supplierForm" label-width="120px" class="supplier-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="账户名称">
                                <el-input v-model="supplierForm.financeName" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纳税人识别号">
                                <el-input v-model="supplierForm.taxpayerNumber" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="银行账户">
                                <el-input v-model="supplierForm.bankAccount" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="开户银行">
                                <el-input v-model="supplierForm.accountBank" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="开户行地址">
                                <el-input v-model="supplierForm.bankAddress" placeholder="请输入" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <!-- 上传附件部分 -->
            <el-card class="form-card" shadow="never">
                <div class="section-header">
                    <h3 class="section-title">上传附件</h3>
                </div>
                <div class="upload-section">
                    <el-upload ref="uploadRef" :action="uploadAction" :headers="uploadHeaders" :file-list="fileList"
                        :on-success="handleUploadSuccess" :on-remove="handleRemove" :before-upload="beforeUpload"
                        :limit="10" multiple class="upload-component">
                        <el-button type="primary">上传</el-button>
                        <template #tip>
                            <div class="upload-tip">
                                您可以上传doc, pdf, rar等格式的文件,单个文件上传最大200MB。
                            </div>
                        </template>
                    </el-upload>

                    <div v-if="fileList.length > 0" class="file-list">
                        <div v-for="(file, index) in fileList" :key="file.uid || index" class="file-item">
                            <el-link :href="file.url" target="_blank" type="primary" :underline="false"
                                class="file-link">
                                {{ file.name }}
                            </el-link>
                            <el-icon class="delete-icon" @click="handleRemoveFile(index)">
                                <Delete />
                            </el-icon>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 底部固定操作按钮 -->
        <div class="footer-actions">
            <el-button @click="handleClose">关闭</el-button>
            <el-button type="success" @click="saveSupplier">保存</el-button>
        </div>

        <!-- 进货部门选择对话框 -->
        <el-dialog v-model="showOrgDialog" title="选择进货部门" width="600px">
            <div style="margin-bottom: 16px;">
                <el-input v-model="orgSearchText" placeholder="搜索部门名称" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <el-tree :data="filteredOrgTree" node-key="organizationId" :props="orgTreeProps" highlight-current
                default-expand-all :expand-on-click-node="false" :current-node-key="selectedOrgNode?.organizationId"
                @node-click="handleSelectOrgNode" style="max-height: 360px; overflow: auto;" />
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showOrgDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmOrgSelection">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 进货负责人选择对话框 -->
        <el-dialog v-model="showUserDialog" title="选择进货负责人" width="400px">
            <div style="margin-bottom: 16px;">
                <el-input v-model="userSearchText" placeholder="搜索用户名称" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <el-table :data="filteredUserList" @row-click="handleSelectUser" highlight-current-row
                style="cursor: pointer;">
                <el-table-column prop="userName" label="负责人姓名" />
            </el-table>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>

import { reactive, ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type UploadInstance } from 'element-plus'
import { Delete, Search } from '@element-plus/icons-vue'
import myaxios from '@/http/MyAxios'
import moment from 'moment'

const route = useRoute()
const router = useRouter()

// 表单引用
const supplierFormRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()
const generatingSupplierCode = ref(false)

// 表单数据
const supplierForm = reactive({
    supplierId: '',
    supplierCode: '',
    supplierName: '',
    industryId: '',
    supplierTypeId: '',
    contact: '',
    contactNumber: '',
    supplierEmail: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    supplierStatus: 0,
    supplierAddress: '',
    remarks: '',
    SupplierNote: '',
    // 财务信息
    financeId: '',
    financeName: '',
    taxpayerNumber: '',
    bankAccount: '',
    accountBank: '',
    bankAddress: '',
    // 操作信息
    createor: '',
    createrTime: '',
})

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
    const now = new Date()
    const segments = (rule?.timeRule || '')
        .split(',')
        .map((s: string) => s.trim().toUpperCase())
        .filter(Boolean)
        .sort((a: string, b: string) => {
            const indexA = TIME_SEGMENT_ORDER.indexOf(a)
            const indexB = TIME_SEGMENT_ORDER.indexOf(b)
            if (indexA === -1 && indexB === -1) return 0
            if (indexA === -1) return 1
            if (indexB === -1) return -1
            return indexA - indexB
        })

    const datePart = segments
        .map((seg: string) => {
            switch (seg) {
                case 'YYYY': return String(now.getFullYear())
                case 'YY': return String(now.getFullYear()).slice(-2)
                case 'MM': return pad(now.getMonth() + 1)
                case 'DD': return pad(now.getDate())
                case 'HH': return pad(now.getHours())
                case 'MI': return pad(now.getMinutes())
                case 'SS': return pad(now.getSeconds())
                default: return ''
            }
        })
        .join('')

    const seq = '1'.padStart(rule?.serialLength || 3, '0')
    return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
    try {
        const res = await myaxios.get('/api/Number/GenerateNumber', {
            params: { targetCode, targetName }
        })
        if (res?.data?.code === 200 && res?.data?.data) {
            return String(res.data.data)
        }
        throw new Error(res?.data?.message || '生成编号失败')
    } catch (err) {
        console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
        const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
            params: { targetCode, targetName }
        })
        const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
        if (list.length > 0) {
            return buildCodeFromRule(list[0])
        }
        throw new Error('未找到对应的编号规则，请先配置编号规则')
    }
}

const generateSupplierCode = async () => {
    if (generatingSupplierCode.value) return
    generatingSupplierCode.value = true
    try {
        supplierForm.supplierCode = await requestNumber('Supplier', '供应商')
        ElMessage.success('编号生成成功')
    } catch (err: any) {
        ElMessage.error(err?.message || '生成编号失败')
    } finally {
        generatingSupplierCode.value = false
    }
}


// 表单验证规则
const rules = {
    supplierName: [
        { required: true, message: '请输入供应商名称', trigger: 'blur' }
    ],
    industryId: [
        { required: true, message: '请选择所属行业', trigger: 'change' }
    ],
    supplierTypeId: [
        { required: true, message: '请选择供应商分类', trigger: 'change' }
    ],
}

// 接口类型定义
interface IndustryItem {
    industryId: string | number
    industryName: string
}

interface SupplierTypeItem {
    supplierTypeId: string | number
    supplierTypeName: string
}

interface OrganizationItem {
    organizationId: string | number
    organizationName: string
    organizationCode?: string
    organizationParentId?: string | number | null
    children?: OrganizationItem[]
}

interface UserItem {
    userId: string | number
    userName: string
    organizationId?: string | number
    organizationName?: string
}

// 下拉列表数据
const industryList = ref<IndustryItem[]>([])
const supplierTypeList = ref<SupplierTypeItem[]>([])
const organizationList = ref<OrganizationItem[]>([])
const organizationTreeData = ref<OrganizationItem[]>([])
const userList = ref<UserItem[]>([])
const organizationNameMap = ref<Record<string, string>>({})

// 对话框显示状态
const showOrgDialog = ref(false)
const showUserDialog = ref(false)
const orgSearchText = ref('')
const userSearchText = ref('')

// 文件上传
const uploadAction = ref('api/Supplier/UploadFile') // 根据实际API调整
const uploadHeaders = ref({
    // 如果需要token等认证信息，在这里添加
})
const fileList = ref<Array<{ name: string; url: string; uid?: number; raw?: File }>>([])

const orgTreeProps = {
    label: 'organizationName',
    children: 'children',
}

const selectedOrgNode = ref<OrganizationItem | null>(null)
const organizationMap = ref<Record<string, OrganizationItem>>({})

const buildOrgMap = (list: OrganizationItem[]) => {
    const map: Record<string, OrganizationItem> = {}
    list.forEach((item) => {
        map[String(item.organizationId)] = item
    })
    organizationMap.value = map
    const nameMap: Record<string, string> = {}
    list.forEach((item) => {
        nameMap[String(item.organizationId)] = item.organizationName
    })
    organizationNameMap.value = nameMap
}

const normalizeOrganizationNodes = (nodes: any[]): OrganizationItem[] => {
    const list: OrganizationItem[] = []
    const traverse = (items: any[]) => {
        items.forEach((item) => {
            const normalized: OrganizationItem = {
                ...item,
                organizationId: item.organizationId ?? item.id ?? item.value,
                organizationName: item.organizationName ?? item.label ?? item.name ?? '',
                organizationCode: item.organizationCode ?? item.code ?? '',
                organizationParentId:
                    item.organizationParentId ??
                    item.parentId ??
                    item.pid ??
                    item.parent ??
                    null,
                children: [],
            }
            list.push(normalized)
            if (item.children && item.children.length) {
                traverse(item.children)
            }
        })
    }
    traverse(nodes)
    return list
}

const buildOrgTree = (list: OrganizationItem[]): OrganizationItem[] => {
    const nodeMap = new Map<string | number, OrganizationItem>()
    const tree: OrganizationItem[] = []

    list.forEach((item) => {
        nodeMap.set(item.organizationId, { ...item, children: [] })
    })

    nodeMap.forEach((item) => {
        const parentId = item.organizationParentId
        if (parentId && nodeMap.has(parentId)) {
            const parent = nodeMap.get(parentId)!
            parent.children = parent.children || []
            parent.children.push(item)
        } else {
            tree.push(item)
        }
    })

    return tree
}

const filteredOrgTree = computed(() => {
    if (!orgSearchText.value) return organizationTreeData.value
    const keyword = orgSearchText.value.toLowerCase()

    const filterTree = (nodes: OrganizationItem[]): OrganizationItem[] => {
        const res: OrganizationItem[] = []
        nodes.forEach((node) => {
            const match = node.organizationName.toLowerCase().includes(keyword)
            const children = node.children ? filterTree(node.children) : []
            if (match || children.length) {
                res.push({ ...node, children })
            }
        })
        return res
    }

    return filterTree(organizationTreeData.value)
})

// 过滤用户列表
const filteredUserList = computed(() => {
    let list = userList.value
    if (supplierForm.organizationId) {
        list = list.filter(
            (user) =>
                user.organizationId &&
                String(user.organizationId) === String(supplierForm.organizationId),
        )
    }
    if (userSearchText.value) {
        const keyword = userSearchText.value.toLowerCase()
        list = list.filter((user) => user.userName.toLowerCase().includes(keyword))
    }
    return list
})

const applyOrgNameToUsers = () => {
    if (!userList.value.length) return
    userList.value = userList.value.map((item) => {
        const orgId =
            item.organizationId ??
            (item as any).organizationID ??
            (item as any).orgId ??
            (item as any).departmentId ??
            ''
        const normalizedOrgId = orgId ? String(orgId) : ''
        return {
            ...item,
            organizationId: normalizedOrgId,
            organizationName:
                item.organizationName ||
                (normalizedOrgId ? organizationNameMap.value[normalizedOrgId] : '') ||
                '',
        }
    })
}

const isRootDictionary = (item: any) =>
    !item.parentId || item.parentId === 0 || item.parentId === '0' || item.parentId === null

const matchDictionary = (item: any, names: string[], codes: string[]) => {
    const name = (item.dictionaryName || '').toLowerCase()
    const code = (item.dictionaryCode || '').toLowerCase()
    return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
        codes.some(c => code === c.toLowerCase())
}

const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
    const params = { Pageindex: 1, PageSize: 1000 }
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
        const list = res.data?.data?.data || []
        const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
        if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
        console.warn('获取字典列表失败', error)
    }

    for (const name of nameCandidates) {
        try {
            const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
            })
            const list = res.data?.data?.data || []
            const found = list.find((item: any) => isRootDictionary(item))
            if (found?.dictionaryId) return found.dictionaryId
        } catch (error) {
            console.warn(`按名称 ${name} 获取字典失败`, error)
        }
    }
    return null
}

const fetchDictionaryChildren = async (parentId: string | number | null) => {
    if (!parentId) return []
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
            params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
        })
        return res.data?.data?.data || []
    } catch (error) {
        console.warn('获取字典子项失败', error)
        return []
    }
}

const loadIndustryList = async () => {
    const parentId = await findDictionaryParentId(['所属行业', '行业'], ['industry'])
    const children = await fetchDictionaryChildren(parentId)
    industryList.value = children.map((item: any) => ({
        industryId: item.dictionaryId,
        industryName: item.dictionaryName
    }))
}

const loadSupplierTypeList = async () => {
    const parentId = await findDictionaryParentId(['供应商分类', '供应商类型'], ['suppliertype', 'supplier_type'])
    const children = await fetchDictionaryChildren(parentId)
    supplierTypeList.value = children.map((item: any) => ({
        supplierTypeId: item.dictionaryId,
        supplierTypeName: item.dictionaryName
    }))
}
// 获取部门列表
const getOrganizationList = () => {
    // 根据实际API调整，如果API不存在，可以从用户列表中获取部门信息
    myaxios.get('api/Supplier/GetOrganization').then((res: any) => {
        if (res.data.code === 200) {
            const rawList = res.data.data || []
            organizationList.value = rawList
            const normalized = normalizeOrganizationNodes(rawList)
            buildOrgMap(normalized)
            const tree = buildOrgTree(normalized)
            organizationTreeData.value = tree.length ? tree : normalized
            applyOrgNameToUsers()
        }
    }).catch((err: any) => {
        console.error('获取部门列表失败:', err)
        // 如果API不存在，可以设置默认数据或留空
        organizationList.value = []
    })
}

// 获取用户列表
const getUserList = () => {
    myaxios.get('api/Supplier/GetUser').then((res: any) => {
        if (res.data.code === 200) {
            userList.value = res.data.data || []
            applyOrgNameToUsers()
        }
    }).catch((err: any) => {
        console.error('获取用户列表失败:', err)
    })
}

// 打开部门选择对话框
const openOrgDialog = () => {
    orgSearchText.value = ''
    const currentOrgId = supplierForm.organizationId
    const mapValue = currentOrgId ? organizationMap.value[String(currentOrgId)] : null
    selectedOrgNode.value = mapValue ?? null
    showOrgDialog.value = true
}

// 打开用户选择对话框
const openUserDialog = () => {
    userSearchText.value = ''
    if (!supplierForm.organizationId) {
        ElMessage.warning('请先选择进货部门')
        return
    }
    showUserDialog.value = true
}

const handleSelectOrgNode = (node: OrganizationItem) => {
    selectedOrgNode.value = node
}

const confirmOrgSelection = () => {
    if (!selectedOrgNode.value) {
        ElMessage.warning('请先选择部门')
        return
    }
    supplierForm.organizationId = String(selectedOrgNode.value.organizationId)
    supplierForm.organizationName = selectedOrgNode.value.organizationName
    supplierForm.userId = ''
    supplierForm.userName = ''
    showOrgDialog.value = false
}

// 选择用户
const handleSelectUser = (row: UserItem) => {
    supplierForm.userId = String(row.userId)
    supplierForm.userName = row.userName
    showUserDialog.value = false
}

// 文件上传前验证
const beforeUpload = (file: File) => {
    const isValidType = ['application/msword', 'application/pdf', 'application/x-rar-compressed',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
        .includes(file.type) || file.name.endsWith('.doc') || file.name.endsWith('.pdf') ||
        file.name.endsWith('.rar') || file.name.endsWith('.docx')
    const isLt200M = file.size / 1024 / 1024 < 200

    if (!isValidType) {
        ElMessage.error('只能上传doc, pdf, rar格式的文件!')
        return false
    }
    if (!isLt200M) {
        ElMessage.error('文件大小不能超过200MB!')
        return false
    }
    return true
}

// 文件上传成功
const handleUploadSuccess = (response: any, file: any, fileListParam: any) => {
    // el-upload会自动更新file-list，这里只需要处理响应
    // 根据实际API响应格式调整
    if (response) {
        if (response.code === 200 || response.status === 'success') {
            ElMessage.success('文件上传成功')
            // 更新文件URL（如果API返回了URL）
            if (response.data?.url) {
                const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
                if (index > -1 && fileList.value[index]) {
                    fileList.value[index].url = response.data.url
                }
            }
        } else {
            ElMessage.error(response.message || '文件上传失败')
            // 从列表中移除失败的文件
            const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
            if (index > -1) {
                fileList.value.splice(index, 1)
            }
        }
    } else {
        // 如果API没有返回响应，假设上传成功
        ElMessage.success('文件上传成功')
    }
}

// 移除文件（手动删除）
const handleRemoveFile = (index: number) => {
    fileList.value.splice(index, 1)
    ElMessage.success('文件已移除')
}

// 文件移除回调（el-upload自动调用）
const handleRemove = (file: any) => {
    const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
    if (index > -1) {
        fileList.value.splice(index, 1)
    }
}

// 关闭
const handleClose = () => {
    router.back()
}
// 准备财务数据
const prepareFinanceData = (supplierId: string | number) => {
    return {
        financeId: supplierForm.financeId || undefined,
        supplierId: supplierId,
        financeName: supplierForm.financeName,
        taxpayerNumber: supplierForm.taxpayerNumber,
        bankAccount: supplierForm.bankAccount,
        accountBank: supplierForm.accountBank,
        bankAddress: supplierForm.bankAddress,
    }
}

// 保存供应商信息
const saveSupplier = async () => {
    if (!supplierForm.supplierCode) {
        await generateSupplierCode()
        if (!supplierForm.supplierCode) {
            ElMessage.warning('请先生成供应商编码')
            return
        }
    }
    try {
        // 自动设置操作人和操作时间 - 从后端获取真实姓名
        let currentUser = localStorage.getItem('username') || ''
        try {
            const res = await myaxios.get('/api/User/GetMyProfile')
            const droot: any = res?.data ?? {}
            const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
            if (d) {
                // 优先使用真实姓名，其次用户名
                currentUser = d.userName || d.realName || d.nickname || currentUser
                // 更新localStorage以便后续使用
                if (currentUser) {
                    localStorage.setItem('username', currentUser)
                }
            }
        } catch (error) {
            console.warn('获取当前用户信息失败，使用本地存储的值:', error)
        }
        const currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
        
        // 更新表单数据中的操作人和操作时间
        supplierForm.createor = currentUser
        supplierForm.createrTime = currentTime
        
        const submitData = {
            ...supplierForm,
            createor: currentUser,
            createrTime: currentTime
        }
        
        const res = await myaxios.post('/api/Supplier/CreateSupplierWithFinance', submitData)
        if (res.data.code === 200) {
            ElMessage.success(res.data.message)
            router.push('/GetSupplier')
        } else {
            ElMessage.error(res.data.message || '保存失败')
        }
    } catch (error: any) {
        console.error('保存供应商信息失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '保存供应商信息失败'
        ElMessage.error(errorMessage)
        throw new Error(errorMessage)
    }
}





// 初始化数据
onMounted(() => {
    loadIndustryList()
    loadSupplierTypeList()
    getOrganizationList()
    getUserList()

    // 如果是编辑模式，获取供应商信息
    if (route.query.supplierId) {
        // 加载供应商信息
        // myaxios.get(`/api/Supplier/GetSupplierById?id=${route.query.supplierId}`).then((res: any) => {
        //     if (res.data.code === 200) {
        //         Object.assign(supplierForm, res.data.data)
        //     }
        // })
    }
})
</script>

<style scoped>
.create-supplier-container {
    min-height: calc(100vh - 60px);
    background-color: #f5f7fa;
    padding: 20px;
    padding-bottom: 80px;
    /* 为底部按钮留出空间 */
}

.form-wrapper {
    max-width: 1200px;
    margin: 0 auto;
}

.form-card {
    margin-bottom: 20px;
    border-radius: 8px;
}

.section-header {
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 2px solid #e4e7ed;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.supplier-form {
    padding: 0 10px;
}

.readonly-input {
    background-color: #f5f7fa;
}

/* 上传附件样式 */
.upload-section {
    padding: 0 10px;
}

.upload-component {
    margin-bottom: 20px;
}

.upload-tip {
    margin-top: 8px;
    color: #909399;
    font-size: 12px;
}

.file-list {
    margin-top: 16px;
}

.file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    margin-bottom: 8px;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
    transition: all 0.2s;
}

.file-item:hover {
    background-color: #f5f7fa;
    border-color: #c0c4cc;
}

.file-link {
    flex: 1;
    font-size: 14px;
    color: #606266;
}

.delete-icon {
    cursor: pointer;
    color: #909399;
    font-size: 16px;
    margin-left: 12px;
    transition: color 0.2s;
}

.delete-icon:hover {
    color: #f56c6c;
}

/* 底部操作按钮 */
.footer-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 16px 20px;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    z-index: 1000;
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
}

/* 输入框样式 */
:deep(.el-input__inner) {
    border-radius: 4px;
}

:deep(.el-textarea__inner) {
    border-radius: 4px;
}

/* 选择器样式 */
:deep(.el-select) {
    width: 100%;
}

/* 单选框样式 */
:deep(.el-radio) {
    margin-right: 20px;
}

/* 对话框表格样式 */
:deep(.el-table__row) {
    cursor: pointer;
}

:deep(.el-table__row:hover) {
    background-color: #f5f7fa;
}
</style>
